<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col :span="4">
                <el-select v-model="selectedType" placeholder="选择账号状态" @change="handleFilterChange"
                    class="filter-select">
                    <el-option label="所有角色" value=""></el-option>
                    <el-option label="旅行社" value="旅行社"></el-option>
                    <el-option label="定制官" value="定制官"></el-option>
                    <el-option label="普通用户" value="普通用户"></el-option>
                </el-select>
            </el-col>
            <el-col :offset="14" :span="4">
                <el-input v-model="searchName" placeholder="请输入用户名称" />
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="sortedUsers" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%"
                @sort-change="handleSortChange">
                <el-table-column property='uId' label="用户ID" />
                <el-table-column property="uName" label="用户名称" />
                <el-table-column property="uPhone" label="用户电话号码" />
                <el-table-column property="uPwd" label="用户密码" />
                <el-table-column property="uFollowing" label="关注人数" />
                <el-table-column property="uFollower" label="粉丝人数" />
                <el-table-column property="lastLogtime" label="上次登录时间" sortable="custom" />
                <el-table-column property="uRole" label="用户角色" />
                <el-table-column property="status" label="账号状态">
                    <template #default="scope">
                        <span class="status-container">
                            <el-icon size="20">
                                <CircleCheck :class="getStatusIconClass(scope.row.status)" />
                            </el-icon>
                            <span>{{ getStatusText(scope.row.status) }}</span>
                        </span>
                    </template>
                </el-table-column>
                <!-- 操作按钮 -->
                <el-table-column width="250" label="操作">
                    <template #default="{ row }">
                        <!-- 删除 -->
                        <el-button type="danger" @click="handleDeleteApplication(row)" :disabled="row.status !== '禁用'"
                            link>
                            删除
                        </el-button>
                        <!-- 禁用 -->
                        <el-button type="warning" @click="handleAbandonQualification(row)"
                            :disabled="row.status == '禁用'" link>
                            禁用
                        </el-button>
                        <!-- 解封 -->
                        <el-button type="success" @click="handleApproveApplication(row)" :disabled="row.status == '激活'"
                            link>
                            解封
                        </el-button>
                        <el-button type="info" @click="handleResetApplication(row)" :disabled="row.status !== '激活'"
                            link>
                            重置密码
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);

// 定义选中的下拉框值
const selectedType = ref('');
// 获取数据的函数
const fetchData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/users/filter', {
            params: {
                uRole: selectedType.value,
            },
        });
        tableData.value = response.data.users;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

// 处理下拉框变化的函数
const handleFilterChange = () => {
    fetchData();
};

const getData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/users/getByPage', {
            params: {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
            },
        });
        tableData.value = response.data.records;
        total.value = response.data.total;
        pageNum.value = response.data.current;
        pageSize.value = response.data.size;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
    getData();
};
const handleCurrentChange = () => {
    getData();
};

const handleSearch = async () => {
    try {
        const response = await axios.get('http://localhost:8088/users/getByName', { params: { uName: searchName.value } });
        tableData.value = response.data;
    } catch (error) {
        console.error('查找出错:', error);
    }
};

// 更新操作的函数
const updateUserStatus = async (uId, status) => {
    try {
        // 构建包含ID和新状态的请求体
        const requestBody = {
            uId,
            status,
        };

        const response = await axios.put(
            "http://localhost:8088/users/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("操作成功");
            // 同步更新表格s中的数据状态
            const users = tableData.value.find((item) => item.uId === uId);
            if (users) {
                users.status = status;
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("操作失败"); // 更新失败，给用户反馈
        return null;
    }
};

// 删除
const handleDeleteApplication = (row) => {
    updateUserStatus(row.uId, '禁用');
};

// 禁用
const handleAbandonQualification = (row) => {
    updateUserStatus(row.uId, '禁用');
};

// 解封
const handleApproveApplication = (row) => {
    updateUserStatus(row.uId, '激活');
};

const updateUserPsw = async (uId) => {
    try {
        // 构建包含ID和新密码的请求体
        const requestBody = {
            uId,
            uPwd: "123456" // 直接设置新密码为 "123456"
        };

        const response = await axios.put(
            "http://localhost:8088/users/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            // 同步更新表格中的数据状态
            const users = tableData.value.find((item) => item.uId === uId);
            if (users) {
                users.uPwd = "123456"; // 直接设置密码为 "123456"
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("操作成功");// 更新失败，给用户反馈
        return null;
    }
};

//忘记密码
const handleResetApplication = (row) => {
    updateUserPsw(row.uId); 
};

// 组件挂载后获取初始数据
onMounted(() => {
    fetchData();
    getData();
});


// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedUsers = computed(() => {
    return tableData.value.slice().sort((a, b) => {
        if (sortProp.value === 'lastLogtime') {
            const timeA = new Date(a.lastLogtime).getTime();
            const timeB = new Date(b.lastLogtime).getTime();
            return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
        }
        return 0;
    });
});

// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
    sortProp.value = newSortInfo.prop;
    sortOrder.value = newSortInfo.order;
};
//处理状态栏样式
function getStatusIconClass(status) {
    switch (status) {
        case '激活':
            return 'status-icon-green';
        case '待审核':
            return 'status-icon-red';
        case '禁用':
            return 'status-icon-gray';
    }
}
function getStatusText(status) {
    switch (status) {
        case '激活':
            return '激活';
        case '待审核':
            return '待审核';
        case '禁用':
            return '禁用';
    }
}

const handleEdit = (row) => {
    // 编辑操作的逻辑
    console.log('Editing row:', row);
};
const handleDelete = (row) => {
    // 删除操作的逻辑
    console.log('Deleting row:', row);
};
</script>

<style scoped>
.el-header {
    padding-left: 0px;
    padding-right: 0px;
}

.el-main {
    background-color: #F2F2F2;
}

.el-aside {
    background-color: #7162A7;
    width: auto;
}

.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.div-view-search {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}



.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 图标特定类，仅用于图标 */
.status-icon-green {
    color: green;
    margin-right: 5px;
    /* 图标和文本之间的间距 */
}

.status-icon-red {
    color: red;
    margin-right: 5px;
}

.status-icon-gray {
    margin-right: 5px;
    color: gray;
}
</style>